<template>
  <div class="start-box">
    <div class="star" v-if="startType==1">
      <span v-for="(itemClass,index) in itemClasses" :key="index" :class="itemClass" class="star-item"
            @click="rating(index)"></span>
      <div class="total">{{score*2}}分</div>
    </div>

    <div class="star" v-if="startType==2">
      <span v-for="(itemClass,index) in itemClassList" :key="index" :class="itemClass" class="star-item"></span>
      <div class="total">{{totalScore*2}}分</div>
    </div>
  </div>

</template>

<script>
  const LENGTH = 5;
  const CLS_ON = 'on';
  const CLS_HALF = 'half';
  const CLS_OFF = 'off';

  export default {
    props: {
      startType: {
        type: Number,
        default: 0
      },
      totalScore: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        score: "",
        half: true,
      };
    },
    methods: {
      rating(index) {//计算评分
        if (this.half) {
          this.half = false;
          this.score = index + 0.5;
        } else {
          this.half = true;
          this.score = index + 1;
        }
        this.$emit("countScore",this.score);
      }
    },
    computed: {
      itemClasses() {//计算星星
        let itemClasses = [];
        let score = Math.floor(this.score * 2) / 2;
        for (let i = 1; i <= score; i++) {//整数星星使用on
          itemClasses.push(CLS_ON);
        }
        if (score % 1 != 0) {//非整数星星使用half
          itemClasses.push(CLS_HALF);
        }
        while (itemClasses.length < LENGTH) {//余下的用无星星补全,使用off
          itemClasses.push(CLS_OFF);
        }
        return itemClasses;
      },
      itemClassList() {
        let itemClasses = [];
        let score = Math.floor(this.totalScore * 2) / 2;
        for (let i = 1; i <= score; i++) {//整数星星使用on
          itemClasses.push(CLS_ON);
        }
        if (score % 1 != 0) {//非整数星星使用half
          itemClasses.push(CLS_HALF);
        }
        while (itemClasses.length < LENGTH) {//余下的用无星星补全,使用off
          itemClasses.push(CLS_OFF);
        }
        return itemClasses;
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .star
    display: flex
    align-items: center
    .star-item
      display: inline-block
      background-repeat: no-repeat
      margin-right: 0.24rem
      width: 0.48rem
      height: 0.48rem
      background-size: 100% 100%
      &.on
        background-image: url("./star_on.png")
      &.off
        background-image: url("./star_off.png")
      &.half
        background-image: url("./star_half.png")
      &:last-child
        margin: 0
    .total
      display: flex
      align-items: center
      font-size: 0.373rem
      font-weight: 500
      color: rgba(250, 191, 72, 1)
</style>
